package android.dj.lbscamera.activities;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.PendingIntent;
import android.app.AlertDialog.Builder;
import android.app.PendingIntent.CanceledException;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.dj.lbscamera.R;
import android.dj.lbscamera.connection.LBSCameraService;
import android.dj.lbscamera.network.ResourceManager;
import android.dj.lbscamera.utils.Constants;
import android.dj.lbscamera.utils.NetWorkUtil;
import android.dj.lbscamera.utils.UseUtils;
import android.dj.lbscamera.widgets.DragView;
import android.dj.lbscamera.widgets.GalleryAdapter;
import android.dj.lbscamera.widgets.ImageZoomView;
import android.dj.lbscamera.widgets.SimpleZoomListener;
import android.dj.lbscamera.widgets.ZoomState;
import android.dj.lbscamera.widgets.ZoomStatePan;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.graphics.Bitmap.Config;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.GestureDetector.OnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.Gallery;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

public class PageMain extends BaseActivity implements OnClickListener,
		OnGestureListener {
	private ViewFlipper flipper;
	private static final int CAMERA = 1;
	private static final int GALLERY = 0;
	private static final int FLING_MIN_DISTANCE = 100;
	private static final int FLING_MIN_VELOCITY = 200;
	private GestureDetector detector;
	private ProgressDialog mDialog;

	private Bitmap bitmap;
	private Bitmap getBitmap;

	private View select_pic;
	private LinearLayout edit_pic;
	private View edit_text;
	private View show_pic;
	private LinearLayout ly_select_pic;
	private LinearLayout ly_edit_pic;
	private LinearLayout ly_edit_text;
	private LinearLayout ly_show_pic;
	private ImageButton m_userinfo;
	private ImageView m_near;
	private ImageView m_main;
	private ImageView m_mypost;

	private Button m_camera;
	private Button m_gallery;

	private ImageButton m_turnleft;
	private ImageButton m_turnright;
	private ImageButton m_larger;
	private ImageButton m_smaller;

	private ImageButton m_reselect;
	private Gallery m_gall;
	private Button m_next;

	private TextView m_topnum;
	private TextView m_bottomnum;
	private CheckBox m_checkbox;
	private EditText m_words;
	private EditText m_story;
	private Button m_btn_next;

	private ImageView m_picture1;
	private ImageView m_picture2;
	private TextView m_text;
	private TextView m_location;
	private ImageView m_locationimg;
	private Button m_finish;
	private LinearLayout mHorizontal;
	private LinearLayout mVertical;

	private int index = 0;
	private int maxIndex = 0;
	private boolean isShowWords = true;
	private LocationManager locMan;
	private static final int LOCATION_PERMISSION = 2000;
	private Location loc;
	private String mCurrLat, mCurrLng;
	protected BaseApplication app;
	// private DragView mDragView;
	// private ZoomStatePan zoomState = new ZoomStatePan();

	private ImageView mFirstTip;
	/** Image zoom view */
	private ImageZoomView mZoomView;

	/** Zoom state */
	private ZoomState mZoomState;

	/** Decoded bitmap image */
	private Bitmap mBitmap;

	/** On touch listener for zoom view */
	private SimpleZoomListener mZoomListener;
	private boolean isHorizontal = true;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		mDialog = new ProgressDialog(this);
		mDialog.setMessage("上传明信片...");
		mFirstTip = (ImageView) findViewById(R.id.tip);
		mFirstTip.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				mFirstTip.setVisibility(View.GONE);
			}
		});
		if (!UseUtils.getPreferenceData(this, "dujun", "first", false)) {
			mFirstTip.setVisibility(View.VISIBLE);
			UseUtils.setPreferenceBooleanData(this, "dujun", "first", true);
		}
		app = (BaseApplication) getApplication();
		bitmap = BitmapFactory.decodeResource(getResources(),
				R.drawable.bg_main);
		detector = new GestureDetector(this);
		flipper = (ViewFlipper) this.findViewById(R.id.viewflipper);
		LayoutInflater mInflater = LayoutInflater.from(this);
		select_pic = mInflater.inflate(R.layout.select_pic, null);
		edit_pic = (LinearLayout) mInflater.inflate(R.layout.edit_pic, null);
		edit_text = mInflater.inflate(R.layout.edit_text, null);
		show_pic = mInflater.inflate(R.layout.show_pic, null);
		flipper.addView(select_pic);
		flipper.addView(edit_pic);
		flipper.addView(edit_text);
		flipper.addView(show_pic);
		initView();
		setOnClickListener();
		locMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
	}

	private void setOnClickListener() {
		ly_edit_pic.setOnClickListener(this);
		ly_edit_text.setOnClickListener(this);
		ly_select_pic.setOnClickListener(this);
		ly_show_pic.setOnClickListener(this);
		m_userinfo.setOnClickListener(this);
		m_near.setOnClickListener(this);
		m_main.setOnClickListener(this);
		m_mypost.setOnClickListener(this);

		m_camera.setOnClickListener(this);
		m_gallery.setOnClickListener(this);

		m_turnleft.setOnClickListener(this);
		m_turnright.setOnClickListener(this);
		m_larger.setOnClickListener(this);
		m_smaller.setOnClickListener(this);

		m_reselect.setOnClickListener(this);
		m_next.setOnClickListener(this);

		m_btn_next.setOnClickListener(this);

		m_locationimg.setOnClickListener(this);
		m_finish.setOnClickListener(this);
	}

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.ly_select_pic:
			if (index > 0) {
				for (int i = 0; i < index; i++) {
					showPrevious();
				}
				index = 0;
				setIndexBackground(index);
			}
			break;
		case R.id.ly_edit_pic:
			if (maxIndex >= 1) {
				if (index < 1) {
					showNext();
				} else if (index > 1) {
					showPrevious();
					if (index == 3)
						showPrevious();
				}
				index = 1;
				setIndexBackground(index);
			}
			break;
		case R.id.ly_edit_text:
			if (maxIndex >= 2) {
				if (index < 2) {
					showNext();
					if (index == 0)
						showNext();
				} else if (index > 2)
					showPrevious();
				index = 2;
				setIndexBackground(index);
			}
			break;
		case R.id.ly_show_pic:
			if (maxIndex >= 3) {
				if (index < 3) {
					for (int i = 3; i > index; i--)
						showNext();
					index = 3;
					setIndexBackground(index);
				}
			}
			break;
		case R.id.userinfo:
			Intent intent = new Intent();
			intent.setClass(PageMain.this, PageUserinfo.class);
			startActivity(intent);
			break;
		case R.id.near:
			Intent near = new Intent();
			near.setClass(PageMain.this, PageNear.class);
			startActivity(near);
			break;
		case R.id.main:

			break;
		case R.id.my_post:
			Intent mypost = new Intent();
			mypost.setClass(PageMain.this, PageMyPostcard.class);
			startActivity(mypost);
			PageMain.this.finish();
			break;
		case R.id.camera:
			String status = Environment.getExternalStorageState();
			if (status.equals(Environment.MEDIA_MOUNTED)) {

				Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				// camera.putExtra(MediaStore.EXTRA_OUTPUT,
				// Uri.fromFile(new File("/sdcard/temp.jpg")));
				startActivityForResult(camera, CAMERA);

			} else {
				Toast.makeText(PageMain.this, getString(R.string.no_sdcard),
						Toast.LENGTH_SHORT).show();
			}
			break;
		case R.id.gallery:
			try {
				Intent gallery = new Intent(Intent.ACTION_GET_CONTENT);
				gallery.setType("image/*");
				gallery.addCategory(Intent.CATEGORY_OPENABLE);
				startActivityForResult(gallery, GALLERY);
			} catch (Exception e) {

			}
			break;
		case R.id.turn_left:
			isHorizontal = !isHorizontal;
			mZoomView.bitmapTrunLeft();
			break;
		case R.id.turn_right:
			isHorizontal = !isHorizontal;
			mZoomView.bitmapTurnRight();
			break;
		case R.id.reselect:
			reselectPic();
			break;
		case R.id.nextstep:
			getBitmap = mZoomView.getCutBitmap();
			if (maxIndex == index)
				index = maxIndex = 2;
			else
				index = 2;
			showNext();
			setIndexBackground(index);
			break;
		case R.id.nextsteptoo:
			if (getBitmap != null) {
				m_picture1.setImageBitmap(getBitmap);
				m_picture2.setImageBitmap(getBitmap);
			}
			if (maxIndex == index)
				index = maxIndex = 3;
			else
				index = 3;
			showNext();
			setIndexBackground(index);
			break;
		case R.id.location:
			Uri uri = Uri.parse("geo:" + app.location.getmCurrLat() + ","
					+ app.location.getmCurrLng());
			Intent it = new Intent(Intent.ACTION_VIEW, uri);
			startActivity(it);
			break;
		case R.id.finish:
			if (!mDialog.isShowing())
				mDialog.show();
			if (!NetWorkUtil.isNetworkAvailable()) {
				long name = System.currentTimeMillis();
				File f = new File(Constants.PATH + "/" + name);
				f = UseUtils.convertBitmapToFile(f, getBitmap);
				String before = UseUtils.getPreferenceData(PageMain.this,
						Constants.NAME, Constants.KEY_IMAGE, "");
				UseUtils.setPreferenceStringData(
						PageMain.this,
						Constants.NAME,
						Constants.KEY_IMAGE,
						before + String.valueOf(name) + "$"
								+ app.user.getUid()
								+ m_words.getText().toString() + "$"
								+ m_story.getText().toString() + "$"
								+ (isShowWords ? "0" : "1") + "$" + mCurrLat
								+ "$" + mCurrLng + "#");
			} else {
				new getSkey().execute();
			}
			break;
		case R.id.larger:
			// larger
			// mDragView.bitmapLarger();
			mZoomState.larger();
			mZoomState.notifyObservers();
			break;
		case R.id.smaller:
			// smaller
			// mDragView.bitmapSmaller();
			mZoomState.smaller();
			mZoomState.notifyObservers();
			break;
		default:
			break;
		}
	}

	private void reselectPic() {
		String[] arg0 = { getString(R.string.camera),
				getString(R.string.gallery) };
		new AlertDialog.Builder(PageMain.this)
				.setTitle(getString(R.string.open_style))
				.setItems(arg0, new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {
						switch (which) {
						case 0:
							String status = Environment
									.getExternalStorageState();
							if (status.equals(Environment.MEDIA_MOUNTED)) {

								Intent camera = new Intent(
										MediaStore.ACTION_IMAGE_CAPTURE);
								// camera.putExtra(MediaStore.EXTRA_OUTPUT, Uri
								// .fromFile(new File("/sdcard/temp.jpg")));
								startActivityForResult(camera, CAMERA);

							} else {
								Toast.makeText(PageMain.this,
										getString(R.string.no_sdcard),
										Toast.LENGTH_SHORT).show();
							}
							break;
						case 1:
							try {
								Intent gallery = new Intent(
										Intent.ACTION_GET_CONTENT);
								gallery.setType("image/*");
								gallery.addCategory(Intent.CATEGORY_OPENABLE);
								startActivityForResult(gallery, GALLERY);
							} catch (Exception e) {

							}
							break;
						default:
							break;
						}
					}
				}).show();

	}

	private void setIndexBackground(int index) {
		switch (index) {
		case 0:
			ly_select_pic.setBackgroundResource(R.drawable.bg_step_selected);
			ly_edit_pic.setBackgroundDrawable(null);
			ly_edit_text.setBackgroundDrawable(null);
			ly_show_pic.setBackgroundDrawable(null);
			break;
		case 1:
			ly_select_pic.setBackgroundDrawable(null);
			ly_edit_pic.setBackgroundResource(R.drawable.bg_step_selected);
			ly_edit_text.setBackgroundDrawable(null);
			ly_show_pic.setBackgroundDrawable(null);
			break;
		case 2:
			ly_select_pic.setBackgroundDrawable(null);
			ly_edit_pic.setBackgroundDrawable(null);
			ly_edit_text.setBackgroundResource(R.drawable.bg_step_selected);
			ly_show_pic.setBackgroundDrawable(null);
			break;
		case 3:
			ly_select_pic.setBackgroundDrawable(null);
			ly_edit_pic.setBackgroundDrawable(null);
			ly_edit_text.setBackgroundDrawable(null);
			ly_show_pic.setBackgroundResource(R.drawable.bg_step_selected);
			m_text.setText(isShowWords ? m_words.getText().toString()
					: getString(R.string.nowords));
			if (!isHorizontal) {
				mHorizontal.setVisibility(View.GONE);
				mVertical.setVisibility(View.VISIBLE);
			} else {
				mHorizontal.setVisibility(View.VISIBLE);
				mVertical.setVisibility(View.GONE);
			}
			break;

		default:
			break;
		}
	}

	private void initView() {
		ly_select_pic = (LinearLayout) findViewById(R.id.ly_select_pic);
		ly_edit_pic = (LinearLayout) findViewById(R.id.ly_edit_pic);
		ly_edit_text = (LinearLayout) findViewById(R.id.ly_edit_text);
		ly_show_pic = (LinearLayout) findViewById(R.id.ly_show_pic);
		m_userinfo = (ImageButton) findViewById(R.id.userinfo);
		m_near = (ImageView) findViewById(R.id.near);
		m_main = (ImageView) findViewById(R.id.main);
		m_mypost = (ImageView) findViewById(R.id.my_post);

		m_camera = (Button) select_pic.findViewById(R.id.camera);
		m_gallery = (Button) select_pic.findViewById(R.id.gallery);

		m_turnleft = (ImageButton) edit_pic.findViewById(R.id.turn_left);
		m_turnright = (ImageButton) edit_pic.findViewById(R.id.turn_right);
		m_larger = (ImageButton) edit_pic.findViewById(R.id.larger);
		m_smaller = (ImageButton) edit_pic.findViewById(R.id.smaller);

		m_reselect = (ImageButton) edit_pic.findViewById(R.id.reselect);
		// m_todealimg = (ImageView) edit_pic.findViewById(R.id.todealimg);

		m_gall = (Gallery) edit_pic.findViewById(R.id.gall);
		ArrayList<Integer> img = new ArrayList<Integer>();
		ArrayList<String> text = new ArrayList<String>();
		img.add(R.drawable.bg_normal);
		img.add(R.drawable.bg_polilai);
		img.add(R.drawable.bg_black_white);
		img.add(R.drawable.bg_strong);
		img.add(R.drawable.bg_lomo);
		text.add(getString(R.string.normal));
		text.add(getString(R.string.polilai));
		text.add(getString(R.string.black_white));
		text.add(getString(R.string.strong));
		text.add(getString(R.string.lomo));
		m_gall.setAdapter(new GalleryAdapter(PageMain.this, img, text));
		m_gall.setSelection(2);
		m_gall.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				setBitmapImage(position);
			}
		});
		m_next = (Button) edit_pic.findViewById(R.id.nextstep);

		m_topnum = (TextView) edit_text.findViewById(R.id.top_num_left);
		m_bottomnum = (TextView) edit_text.findViewById(R.id.bottom_num_left);
		m_checkbox = (CheckBox) edit_text.findViewById(R.id.secretshow);
		m_checkbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				isShowWords = isChecked;
			}
		});
		m_words = (EditText) edit_text.findViewById(R.id.words);
		m_words.addTextChangedListener(new TextWatcher() {

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {

			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			public void afterTextChanged(Editable s) {
				m_topnum.setText(String.valueOf(m_words.getText().toString()
						.length())
						+ "/140");
			}
		});
		m_story = (EditText) edit_text.findViewById(R.id.story);
		m_story.addTextChangedListener(new TextWatcher() {

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {

			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			public void afterTextChanged(Editable s) {
				m_bottomnum.setText(String.valueOf(m_story.getText().toString()
						.length())
						+ "/140");
			}
		});
		m_btn_next = (Button) edit_text.findViewById(R.id.nextsteptoo);

		m_picture1 = (ImageView) show_pic.findViewById(R.id.pic1);
		m_picture2 = (ImageView) show_pic.findViewById(R.id.pic2);
		m_text = (TextView) show_pic.findViewById(R.id.text);
		m_location = (TextView) show_pic.findViewById(R.id.location_txt);
		m_locationimg = (ImageView) show_pic.findViewById(R.id.location);
		m_finish = (Button) show_pic.findViewById(R.id.finish);
		mHorizontal = (LinearLayout) show_pic.findViewById(R.id.mhorizontal);
		mVertical = (LinearLayout) show_pic.findViewById(R.id.mvertical);
	}

	protected void setBitmapImage(int position) {
		switch (position) {
		case 0:

		case 1:

		case 2:

		case 3:
			mZoomView.setWithBitmap(position);

			break;

		case 4:
			mZoomView.xuhuaImage();
			break;
		default:
			break;
		}
	}

	private void showNext() {
		this.flipper.setInAnimation(AnimationUtils.loadAnimation(this,
				R.anim.push_left_in));
		this.flipper.setOutAnimation(AnimationUtils.loadAnimation(this,
				R.anim.push_left_out));
		this.flipper.showNext();
	}

	private void showPrevious() {
		this.flipper.setInAnimation(AnimationUtils.loadAnimation(this,
				R.anim.push_right_in));
		this.flipper.setOutAnimation(AnimationUtils.loadAnimation(this,
				R.anim.push_right_out));
		this.flipper.showPrevious();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// if (resultCode == 0)
		// return;
		// if (requestCode == 0) {// 锟斤拷锟�
		// Uri uri = data.getData();
		// } else if (requestCode == 1) {// 锟斤拷锟斤拷
		// File picture = new File(Environment.getExternalStorageDirectory()
		// + "/temp.jpg");
		// Uri uri = Uri.fromFile(picture);
		// }

		if (requestCode == GALLERY || requestCode == CAMERA) {

			// 如果没有选择照片 则不处理
			if (data == null) {
				return;
			}

			Uri uri = data.getData();
			String path = null;
			Cursor mCursor = getContentResolver().query(uri,
					new String[] { MediaStore.Images.Media.DATA }, null, null,
					null);
			if (mCursor.moveToFirst()) {
				path = mCursor.getString(0);
			}

			if (mCursor != null && !mCursor.isClosed()) {
				mCursor.close();
				mCursor = null;
			}

			if (path != null) {
				if (mZoomView == null) {
					mZoomView = (ImageZoomView) findViewById(R.id.zoomview);

					// mDragView = new DragView(this);
					// // mDragView.setOnTouchListener(mZoomListener);
					// LayoutParams params = new LayoutParams(
					// LayoutParams.FILL_PARENT, 300);
					// edit_pic.addView(mDragView, 1, params);
				}
				mZoomState = new ZoomState();
				mZoomListener = new SimpleZoomListener();
				mZoomListener.setZoomState(mZoomState);
				mZoomView.setZoomState(mZoomState);
				FileInputStream fis = null;
				try {
					fis = new FileInputStream(new File(path));
					mBitmap = BitmapFactory.decodeFileDescriptor(fis.getFD());
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				mZoomView.setImage(mBitmap);
				mZoomView.setOnTouchListener(mZoomListener);

				// mDragView.setBitmap(path);
				// mDragView.setZoomState(zoomState);

			}
			if (index == 0) {
				showNext();
			}
			if (maxIndex == index) {
				index = maxIndex = 1;
			} else {
				index = 1;
			}
			setIndexBackground(index);
		}

		// if (requestCode == GALLERY) {// 锟斤拷锟�
		// if (mDragView == null) {
		// mDragView = new DragView(this);
		// LayoutParams params = new LayoutParams(
		// LayoutParams.FILL_PARENT, 300);
		// edit_pic.addView(mDragView, 1, params);
		// }
		// ContentResolver resolver = getContentResolver();
		// try {
		// Uri uri = data.getData();
		// InputStream in = resolver.openInputStream(uri);
		// // Bitmap myBitmap = BitmapFactory.decodeStream(in);
		// // Bitmap head = UseUtils.setBitmapSize(myBitmap, 128, 128);
		// //<<<<<<< .mine
		// // m_todealimg.setImageBitmap(head);
		// mDragView.setBitmap(in);
		// //=======
		// // // m_todealimg.setImageBitmap(head);
		// // mBitmap = myBitmap;
		// // mDragView.setBitmap(myBitmap);
		// //>>>>>>> .r58
		// // myBitmap.recycle() ;
		// // head.recycle() ;
		// if (index == 0)
		// showNext();
		// if (maxIndex == index)
		// index = maxIndex = 1;
		// else
		// index = 1;
		// setIndexBackground(index);
		// } catch (Exception e) {
		// e.printStackTrace();
		// }
		// } else if (requestCode == CAMERA) {// 锟斤拷锟�
		// if (mDragView == null) {
		// mDragView = new DragView(this);
		// LayoutParams params = new LayoutParams(
		// LayoutParams.FILL_PARENT, 300);
		// edit_pic.addView(mDragView, 1, params);
		// }
		// try {
		// // Bundle extras = data.getExtras();
		// // if (extras != null) {
		// // Bitmap photo = extras.getParcelable("data");
		// Bitmap photo = getLoacalBitmap("/sdcard/temp.jpg");
		// FileDescriptor fd = new FileDescriptor();
		// photo = BitmapFactory.decodeFileDescriptor(fd ) ;
		// // ByteArrayOutputStream bos = new ByteArrayOutputStream();
		// // photo.compress(Bitmap.CompressFormat.JPEG, 100, bos);
		// // Bitmap head = UseUtils.setBitmapSize(photo, 300, 214);
		// // m_todealimg.setImageBitmap(photo);
		// mBitmap = photo;
		// mDragView.setBitmap(photo);
		// if (index == 0)
		// showNext();
		// if (maxIndex == index)
		// index = maxIndex = 1;
		// else
		// index = 1;
		// setIndexBackground(index);
		// // }
		// } catch (Exception e) {
		// e.printStackTrace();
		// }
		// }
		else if (requestCode == LOCATION_PERMISSION) {
			if (resultCode == 0) {
				getAddress();
			}

		}
	}

	private void getAddress() {

		checkGPS();
		locMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		if (locMan.isProviderEnabled(LocationManager.GPS_PROVIDER) == true) {
			String serviceName = Context.LOCATION_SERVICE; // 锟斤拷锟斤拷锟斤拷锟�

			locMan = (LocationManager) this.getSystemService(serviceName); // 锟斤拷取位锟斤拷锟斤拷息

			Criteria criteria = new Criteria();
			criteria.setAccuracy(Criteria.ACCURACY_FINE);
			criteria.setAltitudeRequired(false);
			criteria.setBearingRequired(false);
			criteria.setCostAllowed(true);
			criteria.setPowerRequirement(Criteria.POWER_LOW);
			String provider = locMan.getBestProvider(criteria, false);

			loc = locMan.getLastKnownLocation(provider); // 锟斤拷取GPS锟斤拷锟揭伙拷锟街拷锟斤拷锟斤拷锟较�
			if (loc != null) {
				mCurrLat = String.valueOf(loc.getLatitude());
				mCurrLng = String.valueOf(loc.getLongitude());
			} else {
			}

			List<String> listProv = locMan.getAllProviders();
			loc = locMan.getLastKnownLocation(provider);
			for (int intProv = 0; intProv < listProv.size(); intProv++) {
				provider = listProv.get(intProv);
				loc = locMan.getLastKnownLocation(provider);
				if (loc != null)
					break;
			}

			if (loc != null) {
				mCurrLat = String.valueOf(loc.getLatitude());
				mCurrLng = String.valueOf(loc.getLongitude());
				app.location.setmCurrLat(mCurrLat);
				app.location.setmCurrLng(mCurrLng);
				new QueryAddressTask().execute(mCurrLat, mCurrLng);
			}

			LocationListener locationListener = new LocationListener() {

				public void onStatusChanged(String provider, int status,
						Bundle extras) {

				}

				public void onProviderEnabled(String provider) {

				}

				public void onProviderDisabled(String provider) {

				}

				public void onLocationChanged(Location location) {

					if (location != null) {
						mCurrLat = String.valueOf(location.getLatitude());
						mCurrLng = String.valueOf(location.getLongitude());
					} else {
					}

				}
			};

			locMan.requestLocationUpdates(provider, 3000, 50, locationListener);
		}

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (index != 0) {
				index--;
				setIndexBackground(index);
				showPrevious();
				return true;
			} else {
				return super.onKeyDown(keyCode, event);
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	public static Bitmap getLoacalBitmap(String url) {
		try {
			FileInputStream fis = new FileInputStream(url);
			Bitmap bitmap1 = BitmapFactory.decodeStream(fis);
			return bitmap1;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return null;
		}
	}

	@Override
	protected void onResume() {
		getAddress();
		super.onResume();
	}

	private void checkGPS() {
		if (locMan.isProviderEnabled(LocationManager.GPS_PROVIDER) != true) {

			Builder dialog = new AlertDialog.Builder(PageMain.this);
			dialog.setTitle(getString(R.string.tip));
			dialog.setIcon(android.R.drawable.ic_dialog_info);
			dialog.setMessage(getString(R.string.needgps));
			dialog.setPositiveButton(getString(R.string.sure),
					new DialogInterface.OnClickListener() {

						public void onClick(DialogInterface dialog, int which) {

							startActivityForResult(
									new Intent(
											android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS),
									LOCATION_PERMISSION);
							dialog.dismiss();
						}

					});
			dialog.setNegativeButton(getString(R.string.cancle),
					new DialogInterface.OnClickListener() {

						public void onClick(DialogInterface dialog, int which) {
							Toast.makeText(PageMain.this,
									getString(R.string.no_gps),
									Toast.LENGTH_SHORT).show();
							dialog.dismiss();
							UseUtils.setPreferenceBooleanData(PageMain.this,
									Constants.NAME, Constants.KEY_LBS, false);
						}
					});
			if (UseUtils.getPreferenceData(PageMain.this, Constants.NAME,
					Constants.KEY_LBS, true)) {
				dialog.show();
			}

			return;
		}
	}

	private class QueryAddressTask extends AsyncTask<String, Void, String> {

		@Override
		protected String doInBackground(String... params) {

			String result = null;

			result = LBSCameraService.getInstance().getAddressByLocation(
					params[0], params[1]);

			return result;
		}

		@Override
		protected void onPostExecute(String result) {

			if (!TextUtils.isEmpty(result)) {
				app.location.setLocation(result);
			}
			m_location.setText(app.location.getLocation());
			super.onPostExecute(result);
		}
	}

	public boolean onDown(MotionEvent e) {
		return false;
	}

	public void onShowPress(MotionEvent e) {

	}

	public boolean onSingleTapUp(MotionEvent e) {
		return false;
	}

	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		return false;
	}

	public void onLongPress(MotionEvent e) {

	}

	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		if (e1.getX() - e2.getX() > FLING_MIN_DISTANCE
				&& Math.abs(velocityX) > FLING_MIN_VELOCITY) {
			if (index < maxIndex) {
				showNext();
				index++;
				setIndexBackground(index);
			}
		} else if (e2.getX() - e1.getX() > FLING_MIN_DISTANCE
				&& Math.abs(velocityX) > FLING_MIN_VELOCITY) {
			if (index > 0) {
				showPrevious();
				index--;
				setIndexBackground(index);
			}
		}
		return false;
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		return detector.onTouchEvent(event);
	}

	public class getSkey extends AsyncTask<Void, Void, String> {

		@Override
		protected String doInBackground(Void... params) {
			String result = null;
			try {
				result = ResourceManager.getInstance().doGetUploadSKey();
			} catch (Exception e) {
				e.printStackTrace();
			}
			return result;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			String[] params = new String[4];
			params[0] = "2";
			params[1] = "postcard.png";
			if (!TextUtils.isEmpty(result)) {
				try {
					JSONObject mJson = new JSONObject(result);
					JSONObject data = mJson.getJSONObject("data");
					String skey = data.getString("Key");
					params[2] = skey;
					params[3] = app.user.getUid();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				new createPostcard().execute(params);
			}
		}

	}

	public class createPostcard extends AsyncTask<String, Void, String[]> {

		@Override
		protected String[] doInBackground(String... params) {
			String[] mString = new String[2];
			String result = ResourceManager.getInstance().uploadUserImg(
					params[0], params[1], params[2], params[3], bitmap);
			String createResult = "";
			try {
				createResult = ResourceManager.getInstance().doCreatePostcard(
						app.user.getUid(), m_words.getText().toString(),
						m_story.getText().toString(), isShowWords ? "0" : "1",
						mCurrLat, mCurrLng, params[2]);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			mString[0] = result;
			mString[1] = createResult;
			return mString;
		}

		@Override
		protected void onPostExecute(String[] result) {
			// if (result != null && !TextUtils.isEmpty(result[0])) {
			// try {
			// boolean isUploadImg = false;
			// JSONObject mJson = new JSONObject(result[0]);
			// JSONObject mJsonCreate = new JSONObject(result[1]);
			// String mResult = mJson.getString("result");
			// String mResultCreate = mJsonCreate.getString("result");
			// if (!TextUtils.isEmpty(mResult)) {
			// switch (Integer.valueOf(mResult)) {
			// case 0:
			// Toast.makeText(PageMain.this, "failed",
			// Toast.LENGTH_SHORT).show();
			// break;
			// case 1:
			// isUploadImg = true;
			// break;
			//
			// default:
			// break;
			// }
			// }
			// if (!TextUtils.isEmpty(mResultCreate)) {
			// switch (Integer.valueOf(mResultCreate)) {
			// case 0:
			// Toast.makeText(PageMain.this, "failed",
			// Toast.LENGTH_SHORT).show();
			// break;
			// case 1:
			// if (isUploadImg) {
			// Toast.makeText(PageMain.this, "success",
			// Toast.LENGTH_SHORT).show();
			// Intent share = new Intent();
			// share.setClass(PageMain.this, PageShare.class);
			// startActivity(share);
			// }
			// break;
			// default:
			// break;
			// }
			// }
			// } catch (JSONException e) {
			// // TODO Auto-generated catch block
			// e.printStackTrace();
			// }
			// }

			Intent share = new Intent();
			share.setClass(PageMain.this, PageShare.class);
			startActivity(share);
			if (mDialog.isShowing())
				mDialog.dismiss();
			super.onPostExecute(result);
		}

	}

}
